package com.imay.live.view.dialog;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.facebook.common.executors.CallerThreadExecutor;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.datasource.BaseBitmapDataSubscriber;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.imay.base.fragment.BaseDialogFragment;
import com.imay.live.R;
import com.imay.live.activity.MainActivity2;
import com.imay.live.analytics.MobclickAgent;
import com.imay.live.helper.EventHelper;
import com.imay.live.helper.H5Helper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.helper.ThreadManager;
import com.imay.live.model.AdsModel;
import com.imay.live.utils.GlideUtil;
import com.imay.live.utils.TimeUtil;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lzx on 2017/4/28.
 */

public class ShowAdsFragment extends BaseDialogFragment implements View.OnClickListener {
    public static String TAG_MODEL = "tag_model";
    private ImageView iv_close;
    private ImageView imagev;
    private AdsModel adsModel;
    private LinearLayout re_bg;
    private int temp;
    private float cuttscale;

    private OnFragmentDismiss listener;

    public static ShowAdsFragment newInstance(AdsModel model) {
        Bundle args = new Bundle();
        args.putSerializable(TAG_MODEL, model);
        ShowAdsFragment fragment = new ShowAdsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public void setListener(OnFragmentDismiss listener) {
        this.listener = listener;
    }

    public interface OnFragmentDismiss {
        void fragmentDismiss();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ads_layout;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        adsModel = (AdsModel) getArguments().get(TAG_MODEL);
        if (adsModel == null) {
            dismissAllowingStateLoss();
            return;
        }
        imagev = $(R.id.imagev);
        iv_close = $(R.id.iv_close);
        re_bg = $(R.id.re_bg);
        imagev.setOnClickListener(this);
        iv_close.setOnClickListener(this);
        MobclickAgent.onEvent(getActivity(), "ad_open");
        imagev.setAlpha(0f);
        Glide.with(getContext()).load(adsModel.getPhoto()).listener(new RequestListener<Drawable >() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                dismissAllowingStateLoss();
                return false;
            }

            @Override
            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, com.bumptech.glide.load.DataSource dataSource, boolean isFirstResource) {
                ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 150);
                valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator animation) {
                        int value = (int) animation.getAnimatedValue();
                        if (value > temp) {
                            re_bg.setBackgroundColor(Color.argb(temp, 0, 0, 0));
                            float scale = value / 110.0f;
                            if (value >= 130) {
                                if (cuttscale == 0) {
                                    cuttscale = temp / 110.0f;
                                }
                                scale = cuttscale - (scale - cuttscale);
                                if (scale < 1) {
                                    scale = 1.0f;
                                }
                            }
                            temp = value;
                            imagev.setScaleY(scale);
                            imagev.setScaleX(scale);
                            if (scale > 0.1f) {
                                imagev.setAlpha(1f);
                                imagev.setVisibility(View.VISIBLE);
                            }
                            if (value == 150) {
                                imagev.setScaleY(1.0f);
                                imagev.setScaleX(1.0f);
                                iv_close.setVisibility(View.VISIBLE);
                            }
                        }

                    }
                });
                valueAnimator.setDuration(800);
                valueAnimator.start();
                return false;
            }
        }).apply(new RequestOptions().transform(new GlideRoundTransform(getContext()))).into(imagev);

    }

    @Override
    protected boolean isTranslucentBackground() {
        return true;
    }

        public class GlideRoundTransform extends BitmapTransformation {

        private float radius = 0f;

        public GlideRoundTransform(Context context) {
            this(context, 8);
        }

        public GlideRoundTransform(Context context, int dp) {
            super(context);
            this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
        }

        @Override
        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
            return roundCrop(pool, toTransform);
        }

        private Bitmap roundCrop(BitmapPool pool, Bitmap source) {
            if (source == null) return null;

            Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            if (result == null) {
                result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(result);
            Paint paint = new Paint();
            paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
            canvas.drawRoundRect(rectF, radius, radius, paint);
            return result;
        }



            @Override
            public void updateDiskCacheKey(MessageDigest messageDigest) {

            }
        }
    private Bitmap roundCrop(Bitmap source) {
        if (source == null) return null;

        Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        float radius = Resources.getSystem().getDisplayMetrics().density * 8;
        canvas.drawRoundRect(rectF, radius, radius, paint);
        return result;
    }

    @Override
    protected boolean isMatchParent() {
        return true;
    }

    private void close() {
        ValueAnimator valueAnimator = ValueAnimator.ofInt(100, 0);
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                if (value < temp) {
                    temp = value;
                    re_bg.setAlpha(temp * 0.01f);
                }
                if (value == 0) {
                    dismissAllowingStateLoss();
                    if (getActivity() instanceof MainActivity2) {
                        ((MainActivity2) getActivity()).onShowAds();
                    }
                }
            }
        });
        valueAnimator.setDuration(400);
        valueAnimator.start();
        saveModel();

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_close) {
            close();
            MobclickAgent.onEvent(getActivity(), "ad_close");
        } else if (v.getId() == R.id.imagev) {
            H5Helper.startActivity(adsModel.getJumpContent(), getActivity(), adsModel.getTitle());
            close();
            MobclickAgent.onEvent(getActivity(), "ad_click");
        }
    }

    private void saveModel() {
        dismissAllowingStateLoss();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (listener != null) {
            listener.fragmentDismiss();
        }
    }
}
